﻿using System;
using System.Linq;
using Castle.Core.Logging;
using User.EF.Contracts;
using User.EF.Model;

namespace User.EF.Queries
{
    /// <summary>
    /// Queries für die Abfragen für die OAuthMembership Verwaltung.
    /// </summary>
    public class OAuthMembershipQueries : IOAuthMembershipQueries
    {
        #region Member
        /// <summary>
        /// Der Aktuelle ModelContext
        /// </summary>
        public MainModelContainer Context { get; private set; }

        /// <summary>
        /// Der Aktuelle Logger.
        /// </summary>
        public ILogger Logger { get; set; }
        #endregion

        #region Initialize
        public OAuthMembershipQueries(MainModelContainer container)
        {
            if (container == null)
            {
                throw  new NullReferenceException("Container is Null");
            }

            Context = container;
        }
        #endregion

        #region Public Functions
        /// <summary>
        /// Einen User Anhand der providerUserId ermitteln und dem passenden Providernamen
        /// </summary>
        /// <param name="providerUserId">die ProviderUserId nach der gesucht werden soll</param>
        /// <param name="providerName">der Providername nach dem gesucht werden soll</param>
        public Member GetOAuthUser(string providerUserId, string providerName)
        {
            MemberOAuth member = Context.MemberOAuth.FirstOrDefault(p =>
                        p.Provider.ToLower().Trim() == providerName.ToLower().Trim() &&
                        p.ProviderUserId.Trim() == providerUserId.Trim());

            if (member != null)
            {
                return member.Member;
            }

            return null;
        }

        /// <summary>
        /// Speichern der Einstellungen
        /// </summary>
        public bool Save()
        {
            try
            {
                Context.SaveChanges();
                return true;
            }
            catch (Exception exception)
            {
                Logger.Error("Save Exception Member", exception);
                return false;
            }
        }
        #endregion
    }
}
